import 'package:customer/db/entity/CustomerBill.dart';
import 'package:customer/extension/extension_widget.dart';
import 'package:customer/theme.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_gen/gen_l10n/gyy_local.dart';

import '../../constant/edit_constant.dart';
import '../../db/entity/AttributeBean.dart';
import '../../db/entity/CustomerBillAttr.dart';
import '../../db/entity/ProductBean.dart';
import '../../main.dart';
import '../../widgets/gyy_theme.dart';
import '../../widgets/page.dart';
import 'drop_product_list.dart';

/// 客户下单

class BillIndexPage extends StatefulWidget {
  const BillIndexPage({Key? key}) : super(key: key);

  @override
  State<BillIndexPage> createState() => _EditBillPageState();
}

class _EditBillPageState extends State<BillIndexPage> with PageMixin {
  TextEditingController customerController = TextEditingController(); //客户名称
  TextEditingController phoneController = TextEditingController(); //客户电话
  var customerBillDao = database.customerBillDao;
  var customerBillAttrDao = database.customerBillAttrDao;
  //产品
  var productDao = database.productDao;
  List<ProductBean> allProduct = [];
  //订单选中的产品
  List<ProductBean> selectedProducts = [];

  //产品code -> 产品属性map
  Map<ProductBean, Map<String, AttributeBean>> productAttrMap = {};
  bool isOpen = false;

  //加载所有产品
  loadProduct() async {
    allProduct = await database.productDao.findAll();
    debugPrint('所有产品= ' + allProduct.length.toString());
    setState(() {});
  }

  //保存客户订单
  saveCustomerBill(BuildContext context) async {
    // debugPrint('keys = ' + productAttrMap.keys.toString());
    // debugPrint('values = ' + productAttrMap.values.toString());
    var customerName = customerController.text;
    var customerPhone = phoneController.text;
    if (customerName.isEmpty || customerPhone.isEmpty) {
      showMessage(context, StringConstant.inputCustomer);
      return;
    }

    // 产品扩展属性
    // if (productAttrMap.isEmpty) {
    //   showMessage(context, StringConstant.inputProductAttr);
    //   return;
    // }
    //保存运单
    var customerBill = CustomerBill(
      customerName: customerName,
      customerPhone: customerPhone,
      price: 200,
      billDeposit: 50,
      billBalance: 150,
      billDesc: '广告3件，大幅画1件',
      createTime: DateTime.now(),
      updateTime: DateTime.now(),
    );
    int billId = await customerBillDao.insertOne(customerBill);

    //保存运单属性
    List<CustomerBillAttr> attrList = [];
    //循环每一个产品对应的扩展属性
    productAttrMap.forEach((product, attrMap){
      //循环产品的属性
      attrMap.forEach((_, attribute){
        var billAttr = CustomerBillAttr(
          billId: billId,
          productId: product.id!,
          productName: product.productName,
          productCode: product.productCode,
          attributeId: 0,
          attributeValue: attribute.attributeValue,
          attributeName: attribute.attributeName,
          attributeCode: attribute.attributeCode,
          createTime: DateTime.now(),
          updateTime: DateTime.now(),
        );
        attrList.add(billAttr);
      });

    });
    await customerBillAttrDao.insertList(attrList);

    showMessage(context, StringConstant.saveSuccess);
  }

  @override
  void initState() {
    super.initState();
    loadProduct(); //加载所有产品
  }

  @override
  Widget build(BuildContext context) {
    final theme = FluentTheme.of(context);
    return ScaffoldPage.scrollable(
      header: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            GyyLocal.of(context)!.companyName,
            style: theme.typography.title,
          ),
          Text('2022-11-01 01:01:01', style: theme.typography.bodyStrong)
        ],
      ).padding(paddingH20),
      children: [
        sizeBoxV10,
        Row(
          children: [
            Expanded(
                flex: 5, child: GyyTextInput(StringConstant.customerName, customerController)),
            sizeBoxH5,
            Expanded(
                flex: 5, child: GyyTextInput(StringConstant.customerPhone, phoneController)),
            sizeBoxH5,
            FilledButton(
                child: const Text(StringConstant.saveSuccess),
                onPressed: () async {
                  saveCustomerBill(context);
                })
          ],
        ),
        sizeBoxV5,
        Card(
          child: Row(children: [
            subtitle0(content: const Text(StringConstant.chooseProduct)),
            sizeBoxH5,
            SizedBox(
              width: 200.0,
              child: AutoSuggestBox<ProductBean>(
                items: allProduct
                    .map<AutoSuggestBoxItem<ProductBean>>(
                      (bean) => AutoSuggestBoxItem<ProductBean>(
                        value: bean,
                        label: bean.productName,
                      ),
                    ).toList(),
                onSelected: (item) {
                  setState(() => {selectedProducts.add(item.value!)});
                },
              ),
            ),
            spacer,
            subtitle0(
                content: Text(
              '合计：200￥',
              style: TextStyle(color: AppTheme.accentColor),
            )),
          ]),
        ),
        Column(
          children: [...buildSelectedProducts()],
        )
      ],
    );
  }

  //构建选择的产品
  List<Widget> buildSelectedProducts() {
    List<Widget> widgets = [];
    for (var product in selectedProducts) {
      var billProductPage = EditBillProductPage(product, (map) {
        // debugPrint(map.keys.toString());
        // debugPrint(map.values.toString());
        productAttrMap[product] = map;
      });
      widgets.add(billProductPage);
    }
    return widgets;
  }
}
